package com.ds.admin.console.service;

import cn.hutool.core.lang.Assert;
import com.ds.common.exception.DaoErrorEnum;
import com.ds.common.exception.SystemException;
import com.ds.common.util.MapstructUtils;
import com.ds.common.web.request.PageParam;
import com.ds.common.web.response.PageBuilder;
import com.ds.common.web.response.PageInfo;
import com.ds.admin.console.param.ProductSnapshotParam;
import com.ds.admin.console.entity.ProductSnapshot;
import com.ds.admin.console.mapper.ProductSnapshotMapper;
import com.ds.admin.console.vo.ProductSnapshotVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProductSnapshotService {

	private final ProductSnapshotMapper productSnapshotMapper;

	public Long insert(ProductSnapshotParam param) {
		ProductSnapshot entity = MapstructUtils.convert(param, ProductSnapshot.class);
		int count = productSnapshotMapper.insert(entity);
		Assert.isTrue(count > 0, () -> new SystemException(DaoErrorEnum.INSERT_FAILED));
		return entity.getId();
	}

	public Long update(ProductSnapshotParam param) {
		ProductSnapshot entity = MapstructUtils.convert(param, ProductSnapshot.class);
		int count = productSnapshotMapper.updateById(entity);
		Assert.isTrue(count > 0, () -> new SystemException(DaoErrorEnum.UPDATE_FAILED));
		return entity.getId();
	}

	public Long delete(Long id) {
		int count = productSnapshotMapper.deleteById(id);
		Assert.isTrue(count > 0, () -> new SystemException(DaoErrorEnum.DELETE_FAILED));
		return id;
	}

	public ProductSnapshotVo select(Long id) {
		ProductSnapshot entity = productSnapshotMapper.selectById(id);
		return MapstructUtils.convert(entity, ProductSnapshotVo.class);
	}

	public PageInfo<ProductSnapshotVo> selectPage(PageParam<ProductSnapshotParam> param) {
		Page<ProductSnapshotVo> info = PageHelper.startPage(param.getPageNum(), param.getPageSize())
			.doSelectPage(() -> productSnapshotMapper.selects(param.getParam()));
		return PageBuilder.build(info, info.getPages(), info.getTotal(), info.getPages());
	}

}